package com.rederxu.farmer;
import com.rederxu.tools.DisplayUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

/**
 * BaseActivity,希望所有页面均能继承BaseActivity。
 * 提供如下功能：<br/>
 * 1.网络监听，当网络变化时触发onNetworkChanged方法<br/>
 * 2.代码规范，要求将页面初始化写在init中，数据初始化写在initData中，onCreate之后会依次调用<br/>
 * 3.退出功能。如果所有Activity均继承自本BaseActivity的话，在任何页面中调用exit();方法就可以退出APP<br/>
 * 4.showToast(str);方法快速打印Toast<br/>
 * 
 * <h1>注意：</h1>
 * <h1>A.必须有权限：android.permission.ACCESS_NETWORK_STATE</h1>
 * <h1>B.本Activity无需在AndroidManifest.xml中注册</h1>
 * */
public abstract class BaseActivity extends Activity {

	private BroadcastReceiver finishReceiver = null;
	private BroadcastReceiver networkReceiver = null;
	private String exitActionStr = null;
	private boolean isFirstReceiveNetworkStatus = true;
	public Context mContext = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		exitActionStr = this.getPackageName() + ".exit";
		this.mContext = this;
		this.init();
		this.initData();
		this.initFinish();
		this.initNetwork();
		this.initScrollLeft2Back();
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
	        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
	        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); 
		}
	}

	/**
	 * 建议界面初始化的代码写在这里
	 * */
	public abstract void init();

	/**
	 * 数据请求写在这里，建议在网络重新连接时再调用initData一次
	 * */
	public abstract void initData();
	
	/**
	 * 网络变化
	 * <br/>isMobNetConnected 运营商网络是否连接
	 * <br/>isWifiConnected Wifi是否连接
	 * */
	public abstract void onNetworkChanged(boolean isMobNetConnected,boolean isWifiConnected);
	
	private void initNetwork(){
		IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
		networkReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				if(isFirstReceiveNetworkStatus){
					isFirstReceiveNetworkStatus = false;
					return;
				}
				ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		        NetworkInfo  mobNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		        NetworkInfo  wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		        onNetworkChanged(mobNetInfo.isConnected(),wifiNetInfo.isConnected());
			}
		};
        this.registerReceiver(networkReceiver, filter);
	}

	private void initFinish(){
		IntentFilter filter=new IntentFilter(exitActionStr);
		finishReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				finish();
			}
		};
        this.registerReceiver(finishReceiver, filter);
	}
	
	@Override
	public void finish() {
		try{
			this.unregisterReceiver(networkReceiver);
			this.unregisterReceiver(finishReceiver);
		}catch(Exception e){
			e.printStackTrace();
		}
		super.finish();
	}
	
	/**
	 * 快速输出Toast
	 * */
	public void showToast(String str){
		Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
	}
	
	/**
	 * 退出所有继承自BaseActivity的类。当所有页面均继承自BaseActivity时可以退出整个APP
	 * */
	public void exit(){
		Intent intent = new Intent();
		this.sendBroadcast(intent.setAction(exitActionStr));
	}
	
	public void startActivity(Class c){
		startActivity(new Intent(this,c));
	}
	
	public void startActivityForResult(Class c,int requestCode){
		startActivityForResult(new Intent(this,c), requestCode);
	}
	
	/**
	 * 手势相关代码
	 * */
	private boolean isTouch2BackEnable = true;
	private int verticalMinDistance = 220;  
	private int minVelocity         = 0;
	private void initScrollLeft2Back(){
		ViewGroup view = (ViewGroup) getWindow().getDecorView();
        View v = view.getChildAt(0);
        @SuppressWarnings("deprecation")
		final GestureDetector mGestureDetector = new GestureDetector(new OnGestureListener() {
			
			@Override
			public boolean onSingleTapUp(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onShowPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
					float distanceY) {
				// TODO Auto-generated method stub
				return false;
			}
			
			@Override
			public void onLongPress(MotionEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
					float velocityY) {
						if (e1.getX() - e2.getX() > verticalMinDistance
								&& Math.abs(velocityX) > minVelocity) {
						} else if (e2.getX() - e1.getX() > verticalMinDistance
								&& Math.abs(velocityX) > minVelocity) {
							finish();
						}
						return false;
			}
			
			@Override
			public boolean onDown(MotionEvent e) {
				// TODO Auto-generated method stub
				return false;
			}
		});
        v.requestFocus();
        v.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(isTouch2BackEnable){
					mGestureDetector.onTouchEvent(event);
					return true;
				}else{
					return false;
				}
			}
		});
	}

	public boolean isTouch2BackEnable() {
		return isTouch2BackEnable;
	}

	public void setTouch2BackEnable(boolean isTouch2BackEnable) {
		this.isTouch2BackEnable = isTouch2BackEnable;
	}
	
}
